package com.mayikt;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @ClassName MayiktSemaphore
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class MayiktSemaphore {
    private Sync sync;

    public MayiktSemaphore(int count) {
        sync = new Sync(count);
    }

    public void acquire() {
        sync.acquireShared(1);
    }

    public void release() {
        sync.releaseShared(1);
    }

    class Sync extends AbstractQueuedSynchronizer {


        public Sync(int count) {
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            for (; ; ) {
                int oldState = getState();
                int newState = oldState - arg;
                if (compareAndSetState(oldState, newState)) {
                    return newState < 0 ? -1 : 1;
                }
            }

        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            // true false newState>0 true <0
            for (; ; ) {
                int oldState = getState();
                //+1
                int newState = oldState + arg;
                if (newState < oldState) {
                    throw new Error("Maximum permit count exceeded");
                }
                if (compareAndSetState(oldState, newState)) {
                    return true;
//                    return newState>0;
                }

            }

        }
    }

    public static void main(String[] args) {
        // 设置aqs状态为5 只能限制有5线程执行代码  限流 做多可以容量5个人
        MayiktSemaphore semaphore = new MayiktSemaphore(5);
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                // aqs状态会减去1 如果状态=0的情况下
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + ",进入景区成功");
//                // aqs 状态+1 同时唤醒aqs正在阻塞的线程
                semaphore.release();
            }).start();

        }
    }


}
